using System;
using System.Diagnostics;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;

namespace TeamDeploy.Tasks
{
    public class Install : TaskBase
    {
        public Install()
        {
            ExtraArgs = "";
            OverrideDefaultArgs = "";
        }

        public override bool Execute()
        {
            try
            {
                if (!System.IO.File.Exists(RemoteExecutePathFilename))
                {
                    Log.LogError("RemoteExecute does not exists at: " + RemoteExecutePathFilename);
                    return false;
                }

                string installArgs = "/qb! /i";

                if (OverrideDefaultArgs != null && OverrideDefaultArgs.Length > 0)
                {
                    installArgs = OverrideDefaultArgs;
                }

                string psExecArgs = "-i 0 -s -accepteula";

                if (OverridePSExecArgs != null && OverridePSExecArgs.Length > 0)
                {
                    psExecArgs = OverridePSExecArgs;
                }

                string args = @"\\" + TargetMachine + " " + psExecArgs + " " + "msiexec.exe " + installArgs + " " + @"""" + MSIPathFilename + @"""" + " " + ExtraArgs;



                Process p = Process.Start(RemoteExecutePathFilename, args);
                p.WaitForExit();

                if(p.ExitCode != 0)
                {
                    Log.LogMessage("Installing " + MSIPathFilename + " " + args + " on " + TargetMachine + " returned code:" + p.ExitCode);
                }

                if (BuildEngine != null)
                {
                    Log.LogMessage("Installing " + MSIPathFilename + " " + args + " on " + TargetMachine + " completed successfully.");
                }


                return true;
            }
            catch (Exception ex)
            {
                if (BuildEngine != null)
                {
                    Log.LogError("Error executing Install: MSIPathFilename=" + MSIPathFilename + " TargetMachine=" +
                                 TargetMachine + " RemoteExecutePathFilename=" + RemoteExecutePathFilename + ":::" +
                                 ex);
                }
                return false;
            }
        }

        [Required]
        public string MSIPathFilename { get; set; }

        public string ExtraArgs { get; set; }

        [Required]
        public string TargetMachine { get; set; }

        [Required]
        public string RemoteExecutePathFilename { get; set; }

        public string OverrideDefaultArgs { get; set; }

        public string OverridePSExecArgs { get; set; }
    }
}
